package datos;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import datos.interfaces.IAdministradorDAO;
import logica.Administrador;
import logica.Direccion;
import logica.Usuario;


public class JDBCAdministradorDAO implements IAdministradorDAO {

	@Override
	public Administrador obtenerAdministrador(String administradorID) {
		String sql="SELECT * FROM administrador WHERE administradorID=?";
		ConnectionManager conexMan = ConnectionManager.getInstance();
		Connection conexion = conexMan.checkOut();
		
		PreparedStatement ps;
		Administrador admin = new Administrador();
		
		try {
			ps = conexion.prepareStatement(sql);
			ps.setString(1, administradorID);
			ResultSet result=ps.executeQuery();
			
			if(result.next()){
				
				admin.setNombre(result.getString("nombre"));
				admin.setApellidos(result.getString("apellidos"));
				admin.setEmail(result.getString("email"));
				admin.setPassword(result.getString("password"));
		
				
			} else {
				admin=null;
			}
			ps.close();
			result.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return admin;
	}

	@Override
	public String obtenerAdministradorOID(String administradorID,Connection conn) {
		String sql="SELECT OID FROM administrador WHERE administradorID=?";
		ResultSet resultado;
		String oid="";
		try {
			PreparedStatement ps=conn.prepareStatement(sql);
			ps.setString(1,administradorID);
			resultado=ps.executeQuery();
			resultado.next();
			oid=resultado.getString("OID");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return oid;
	}

	@Override
	public Administrador doAdminLogin(String email, String password) {
		ConnectionManager conexMan = ConnectionManager.getInstance();
		Connection conexion=conexMan.checkOut();
		
		String sql="SELECT * FROM administrador WHERE email=? AND password=?";
		ResultSet resultado;
		Administrador admin= null;
		try {
			PreparedStatement ps=conexion.prepareStatement(sql);
			ps.setString(1, email);
			ps.setString(2, password);
			resultado=ps.executeQuery();
			if(resultado.next()){
				admin=this.obtenerAdministrador(resultado.getString("administradorID"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		conexMan.checkIn(conexion);
		return admin;
	}
	

}
